#!/usr/bin/env python3
# -*- coding: utf-8 -*-

debug_level = False

idx_match = 0
idx_display = 1

data_in_files = {
# seq: [match_name, display_name, bigger_better, value]
1: [["TCP STREAM" , 6],                   "TCP Message size"],
2: [["UDP STREAM" , 5],                   "UDP Message size"],
3: [["TCP REQUEST/RESPONSE" , 6],         "TCP_RR"],
4: [["TCP Connect/Request/Response" , 6], "TCP_CRR"],
5: [["UDP REQUEST/RESPONSE" , 6],         "UDP_RR"]
}
data_output = {}

def save_data(_data, line):
    _size = ""
    _display = _data[idx_display]
    if _display == "TCP Message size":
        _size = line.split()[2]
        _tp = line.split()[4]
    elif _display == "UDP Message size":
        _size = line.split()[1]
        _tp = line.split()[5]
    elif _display == "TCP_RR":
        _tp = line.split()[5]
    elif _display == "TCP_CRR":
        _tp = line.split()[5]
    elif _display == "UDP_RR":
        _tp = line.split()[5]

    _key="_"
    _item = "{0:>16} {1:>5}".format(_display, _size)
    _key = _key.join(_item.split())
    _type = "save"
    if _key not in data_output:
        data_output[_key] = []
        _type = "new "
    data_output[_key].append(_tp)
    if debug_level is True:
        print("[{2}] {0:>25} {1}".format( _key, _tp, _type))

def is_new_start(line):
    for seq in data_in_files:
        if data_in_files[seq][idx_match][0] in line:
            return 1
    return 0

def get_netperf_data(file):
    line_num = 0
    header_found = False
    for seq in data_in_files:
        _data = data_in_files[seq]
        with open(file) as f:
            for line in f:
                line = line.strip().strip('\n')
                if header_found is True:
                    if is_new_start(line):
                        if debug_level is True:
                            print("is_new_start: {0}".format(line))
                        header_found = False
                        line_num = 0
                        continue

                    line_num += 1
                    if line_num != _data[idx_match][1]:
                        continue

                    save_data(_data, line)
                    header_found = False
                    line_num = 0
                    continue

                if _data[idx_match][0] in line:
                    line_num = 0
                    header_found = True
                    continue

def show_data():
    if debug_level is True:
        print("\n-------- output single --------\n")
    for i in data_output:
        _data = data_output[i]
        if debug_level is True:
            print("{0} | {1}".format(i, _data))

def analyze_log(file):
    get_netperf_data(file)
    show_data()

def handler_data():
    if debug_level is True:
        print("\n-------- output all --------\n")
    for seq in data_output:
        avg = 0
        total = 0
        print("\n%-41s bigger_better  " % (seq), end='')
        _data = data_output[seq]
        count = len(_data)
        for i in _data:
            print(" %10s " % (i), end='')
            total += float(i)
        avg = float(total / count)
        print(" %10.2f " % (avg), end='')

        for i in _data:
            i_flux = float('%.0f' % (float(abs((float(i) - avg) * 100 / avg))))
            print(" %6.0f%%" % i_flux, end='')
    #print("\n")

def init(dbg):
    global debug_level
    debug_level = dbg
    return analyze_log, handler_data
